package org.example;

import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Solution s = new Solution();
        int calculate = s.calculate("42");
        System.out.println(calculate);
    }
}
class Solution {
    public int calculate(String s) {
        Stack<Integer> stack = new Stack<>();
        char operator = '+';//默认操作符
        int n = s.length();
        for(int i = 0;i < n; i++){
            char ch = s.charAt(i);
            //跳过空格
            if(ch == ' ') continue;
            //替换操作符
            if(ch == '+' || ch == '-' || ch == '*' || ch == '/'){
                operator = ch;

            }else{
                //说明当前是个数字，提取出整个number
                int num = ch - '0';
                i++;
                while(i < n && s.charAt(i) - '0' >= 0 && s.charAt(i) - '0' <= 9) num = num * 10 + s.charAt(i++) - '0';
                i--;
                //根据当前的操作符进行判断
                if(operator == '+'){
                    stack.push(num);
                }

                if(operator == '-'){
                    stack.push(-num);
                }

                if(operator == '*'){
                    int pop = stack.pop();
                    stack.push(num * pop);
                }

                if(operator == '/'){
                    int pop = stack.pop();
                    stack.push(pop / num);
                }

            }

        }

        int ret = 0;

        while(!stack.isEmpty()) ret += stack.pop();

        return ret;
    }
}